import React, { useState, useEffect } from 'react';
import Header from './components/Header';
import RoomControls from './components/RoomControls';
import ScreenSharing from './components/ScreenSharing';
import RoomList from './components/RoomList';
import Footer from './components/Footer';
import WebRTCService from './services/WebRTCService';

// 服务器URL配置检查
const getServerUrl = () => {
  // 首先尝试使用环境变量
  // if (process.env.REACT_APP_SERVER_URL) {
  //   return process.env.REACT_APP_SERVER_URL;
  // }
  //
  // // 然后尝试使用当前页面的主机名配置
  // const currentHost = window.location.hostname;
  // const protocol = window.location.protocol === 'https:' ? 'https' : 'http';
  //
  // // 如果是localhost或IP访问，使用配置的IP地址
  // if (currentHost === 'localhost' || /^(\d{1,3}\.){3}\d{1,3}$/.test(currentHost)) {
  //   return 'http://localhost:5000'; // 您的默认信令服务器地址
  // }
  //
  // // 否则假设和当前页面同域，只是端口不同
  // return `${protocol}://${currentHost}:5000`;
  return "http://192.168.1.208:5000";
};

const SERVER_URL = getServerUrl();

console.log('使用信令服务器URL:', SERVER_URL);

// 检测浏览器WebRTC支持情况
const checkBrowserSupport = () => {
  const supportReport = {
    RTCPeerConnection: !!window.RTCPeerConnection,
    getUserMedia: !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),
    getDisplayMedia: !!(navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia),
    supported: false,
    details: []
  };

  if (!supportReport.RTCPeerConnection) {
    supportReport.details.push('您的浏览器不支持RTCPeerConnection');
  }
  if (!supportReport.getUserMedia) {
    supportReport.details.push('您的浏览器不支持getUserMedia');
  }
  if (!supportReport.getDisplayMedia) {
    supportReport.details.push('您的浏览器不支持屏幕共享');
  }

  supportReport.supported = supportReport.RTCPeerConnection &&
                            supportReport.getUserMedia &&
                            supportReport.getDisplayMedia;

  return supportReport;
};

function App() {
  const [webRTCService, setWebRTCService] = useState(null);
  const [roomId, setRoomId] = useState(null);
  const [isRoomCreator, setIsRoomCreator] = useState(false);
  const [showRoomControl, setShowRoomControl] = useState(true);
  const [connectionStatus, setConnectionStatus] = useState('初始化中...');
  const [webrtcSupport, setWebrtcSupport] = useState(null);

  // 检查浏览器支持
  useEffect(() => {
    const support = checkBrowserSupport();
    setWebrtcSupport(support);

    if (!support.supported) {
      console.warn('浏览器WebRTC支持检查失败:', support.details);
    } else {
      console.log('浏览器支持WebRTC');
    }
  }, []);

  // 初始化WebRTC服务
  useEffect(() => {
    console.log("初始化WebRTC服务，连接到:", SERVER_URL);
    setConnectionStatus(`正在连接到服务器 ${SERVER_URL}...`);

    try {
      const service = new WebRTCService(SERVER_URL);
      setWebRTCService(service);

      // 设置连接状态监听
      service.on('error', (error) => {
        console.error('WebRTC服务错误:', error);
        setConnectionStatus(`连接错误: ${error}`);
      });

      // 尝试ping服务器确认连接
      fetch(`${SERVER_URL}/status`)
        .then(response => {
          if (response.ok) {
            return response.json();
          }
          throw new Error('服务器状态检查失败');
        })
        .then(data => {
          console.log('服务器状态:', data);
          setConnectionStatus(`已连接到服务器，房间数: ${data.rooms}`);
        })
        .catch(error => {
          console.error('服务器连接检查失败:', error);
          setConnectionStatus(`警告: 服务器状态检查失败 - ${error.message}`);
        });

      return () => {
        // 清理
        if (service && roomId) {
          console.log('组件卸载，离开房间:', roomId);
          service.leaveRoom();
        }
      };
    } catch (error) {
      console.error('WebRTC服务初始化失败:', error);
      setConnectionStatus(`服务初始化失败: ${error.message}`);
      return () => {};
    }
  }, []);

  // 处理加入/创建房间
  const handleRoomJoined = (joinedRoomId, isCreator) => {
    if (!joinedRoomId) {
      console.error("错误: 尝试加入空房间ID");
      setConnectionStatus(`错误: 无效的房间ID`);
      return;
    }

    console.log("加入房间:", joinedRoomId, "是创建者:", isCreator);
    setRoomId(joinedRoomId);
    setIsRoomCreator(isCreator);
    setShowRoomControl(false);
    setConnectionStatus(`已加入房间: ${joinedRoomId}, ${isCreator ? '您是创建者' : '您是观看者'}`);
  };

  // 从房间列表选择房间
  const handleRoomSelected = (selectedRoomId) => {
    if (webRTCService) {
      console.log("从列表选择房间:", selectedRoomId);
      webRTCService.joinRoom(selectedRoomId);
      setRoomId(selectedRoomId);
      setIsRoomCreator(false);
      setShowRoomControl(false);
      setConnectionStatus(`已选择并加入房间: ${selectedRoomId}`);
    }
  };

  // 离开房间
  const handleLeaveRoom = () => {
    if (webRTCService) {
      console.log("离开房间:", roomId);
      webRTCService.leaveRoom();
    }
    setRoomId(null);
    setIsRoomCreator(false);
    setShowRoomControl(true);
    setConnectionStatus('已离开房间，回到大厅');
  };

  // 显示浏览器支持问题警告
  const renderBrowserWarning = () => {
    if (!webrtcSupport || !webrtcSupport.supported) {
      return (
        <div className="browser-warning" style={{
          backgroundColor: '#fff3cd',
          color: '#856404',
          padding: '10px',
          borderRadius: '5px',
          marginBottom: '20px'
        }}>
          <h3>⚠️ 浏览器兼容性警告</h3>
          <p>您的浏览器可能不完全支持WebRTC功能，这可能导致屏幕共享无法正常工作。</p>
          <ul>
            {webrtcSupport && webrtcSupport.details.map((detail, index) => (
              <li key={index}>{detail}</li>
            ))}
          </ul>
          <p>建议使用最新版的Chrome、Edge或Firefox浏览器。</p>
        </div>
      );
    }
    return null;
  };

  return (
    <div className="container">
      <Header />

      <div className="connection-status" style={{
        padding: '8px',
        backgroundColor: connectionStatus.includes('错误') ? '#f8d7da' :
                         connectionStatus.includes('警告') ? '#fff3cd' : '#d4edda',
        borderRadius: '4px',
        marginBottom: '15px'
      }}>
        <strong>连接状态:</strong> {connectionStatus}
      </div>

      {renderBrowserWarning()}

      <main>
        {showRoomControl ? (
          <>
            <RoomControls
              webRTCService={webRTCService}
              onRoomJoined={handleRoomJoined}
            />
            <RoomList
              webRTCService={webRTCService}
              onRoomSelected={handleRoomSelected}
            />
          </>
        ) : (
          <>
            <div className="room-header">
              <h2>房间ID: {roomId}</h2>
              <div>
                <div style={{ marginBottom: '8px' }}>
                  <strong>您的角色:</strong> {isRoomCreator ? '共享方 (可以共享屏幕)' : '观看方 (可以查看共享内容)'}
                </div>
                <button
                  className="btn warning"
                  onClick={handleLeaveRoom}
                >
                  离开房间
                </button>
              </div>
            </div>
            <ScreenSharing
              webRTCService={webRTCService}
              isRoomCreator={isRoomCreator}
              roomId={roomId}
            />
          </>
        )}
      </main>

      <div className="debugging-info" style={{ margin: '20px 0', fontSize: '12px', color: '#666' }}>
        <details>
          <summary>调试信息</summary>
          <ul>
            <li><strong>服务器URL:</strong> {SERVER_URL}</li>
            <li><strong>浏览器:</strong> {navigator.userAgent}</li>
            <li><strong>WebRTC支持:</strong> {webrtcSupport ? (webrtcSupport.supported ? '支持' : '不完全支持') : '检测中...'}</li>
            <li><strong>当前房间:</strong> {roomId || '无'}</li>
            <li><strong>角色:</strong> {roomId ? (isRoomCreator ? '创建者(共享方)' : '加入者(观看方)') : '未加入房间'}</li>
          </ul>
          <p>
            <small>* 如果屏幕共享不工作，请确保您正在使用两个不同的浏览器或设备进行测试，一个作为共享方，一个作为观看方。</small>
          </p>
        </details>
      </div>

      <Footer />
    </div>
  );
}

export default App;
